import axios from "axios";
const AUTHORIZATION =
  "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";

axios.defaults.proxy = {
  host: "127.0.0.1",
  port: 10809,
};

/**
 * 获取token
 * 如果发生错误,则返回null
 */
async function getGuestToken(): Promise<string> {
  const API_GUEST = "https://api.twitter.com/1.1/guest/activate.json";
  let res = await axios.post(
    API_GUEST,
    {},
    { headers: { authorization: AUTHORIZATION } }
  );
  console.log("222:", res.data);
  return res.data.guest_token;
}

async function getTimeline(
  name: string,
  count: number,
  token: string
): Promise<any> {
  let url = `https://api.twitter.com/1.1/statuses/user_timeline.json`;
  let res = await axios.get(url, {
    params: {
      screen_name: name,
      count,
    },
    headers: { authorization: AUTHORIZATION, "x-guest-token": token },
    onDownloadProgress: function (event) {
      console.log(event);
    },
  });

  if (res.status !== 200) {
    return null;
  }

  try {
    return typeof res.data === "string" ? JSON.parse(res.data) : res.data;
  } catch (e) {
    console.log(e);
    return null;
  }
}

interface IPhotoEntity {
  text: string;
  type: "photo";
  media_url: string;
}

interface IVideoEntity {
  text: string;
  type: "video";
  video_info: {
    variants: { content_type: "video/mp4"; bitrate: number; url: string }[];
  };
}

/**媒体类型 */
export enum EMediaType {
  photo = "photo",
  video = "video",
}

export interface IMedia {
  id: string;
  type: EMediaType;
  url: string;
  text: string;
}

function format(
  list: {
    text: string;
    id: number;
    extended_entities: {
      media: (IPhotoEntity | IVideoEntity)[];
    };
  }[]
): {
  photos: IMedia[];
  videos: IMedia[];
} {
  let photos: IMedia[] = [];
  let videos: IMedia[] = [];
  list.forEach((info) => {
    let id: string = info.id.toString();
    let text: string = info.text;
    let extended_entities = info.extended_entities;
    if (!extended_entities) {
      return;
    }
    let medias = extended_entities.media;
    // console.log({ medias });
    // photos
    if (medias && medias[0] && medias[0].type === "photo") {
      photos.push(
        ...(medias as IPhotoEntity[]).map((n, i) => {
          return {
            id: id + "" + i,
            type: EMediaType.photo,
            url: n.media_url,
            text,
          };
        })
      );
    }

    // videos
    if (medias && medias[0] && medias[0].type === "video") {
      let variants = medias[0].video_info.variants;
      let videoInfo = variants
        .filter((n) => n.content_type === "video/mp4")
        .reduce((prev, n) => {
          if (!prev || n.bitrate > prev.bitrate) {
            return { ...n };
          }
          return prev;
        }, null);
      if (videoInfo !== null && videoInfo.url) {
        videos.push({ id, type: EMediaType.video, text, url: videoInfo.url });
      }
    }
  });

  return { photos, videos };
}

export { getGuestToken, getTimeline, format };
